//
//  StoreKitToolClass.m
//  QuXiang
//
//  Created by Duncan on 2020/7/28.
//  Copyright © 2020 NanHuaiZi. All rights reserved.
//

#import "StoreKitToolClass.h"
#import <StoreKit/StoreKit.h>

/*注意事项：
1.沙盒环境测试appStore内购流程的时候，请使用没越狱的设备。
2.请务必使用真机来测试，一切以真机为准。
3.项目的Bundle identifier需要与您申请AppID时填写的bundleID一致，不然会无法请求到商品信息。
4.如果是你自己的设备上已经绑定了自己的AppleID账号请先注销掉,否则你哭爹喊娘都不知道是怎么回事。
5.订单校验 苹果审核app时，仍然在沙盒环境下测试，所以需要先进行正式环境验证，如果发现是沙盒环境则转到沙盒验证。
识别沙盒环境订单方法：
 1.根据字段 environment = sandbox。
 2.根据验证接口返回的状态码,如果status=21007，则表示当前为沙盒环境。
 苹果反馈的状态码：
 21000App Store无法读取你提供的JSON数据
 21002 订单数据不符合格式
 21003 订单无法被验证
 21004 你提供的共享密钥和账户的共享密钥不一致
 21005 订单服务器当前不可用
 21006 订单是有效的，但订阅服务已经过期。当收到这个信息时，解码后的收据信息也包含在返回内容中
 21007 订单信息是测试用（sandbox），但却被发送到产品环境中验证
 21008 订单信息是产品环境中使用，但却被发送到测试环境中验证
 */

@interface StoreKitToolClass () <SKProductsRequestDelegate, SKPaymentTransactionObserver>

@property (nonatomic,strong) SKProductsRequest *request;
@property (nonatomic,strong) NSArray *products;
@property (nonatomic,strong) NSMutableSet *purchasedProducts;
@property (nonatomic,strong) SKProduct *product;
@property (nonatomic,copy) NSString *OrderNo; // 订单号

@end

@implementation StoreKitToolClass

kIMSingletonM()

- (instancetype)init {
    self = [super init];
    if (self) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        
        if (WQShare.isLogin) {
            NSString *receiptStr = [DataStoreService getStringById:kDataStoreReceiptData fromTable:Device];
            if (!kIsEmpty(receiptStr)) {
                // 有票据
                [self PayCallBack_iosPayCallBackApi];
            }
        }
    }
    return self;
}

- (void)dealloc {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)applePay:(VDMemberModel *)storeKitModel type:(NSNumber *)type {
    if (![SKPaymentQueue canMakePayments]) {
        [OCProgress_HUD showErrorWithStatus:@"不支持内购"];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [OCProgress_HUD showWithStatus:@"正在购买..."];
    });
    NSMutableDictionary *dictMutal = [NSMutableDictionary dictionaryWithDictionary:@{
        @"way" : @"3",
        @"month" : @"",
        @"type" : type,
    }];
    
    if ([OCUserService share].isVisitorsLogin) {
        [dictMutal setValue:@"ios_check" forKey:@"ios_check"];
    }
    
//    [NetworkService postWithUrlEnumName:Order_buyVip parameters:dictMutal success:^(int code, id  _Nonnull info, NSString * _Nonnull msg) {
//        self.OrderNo = [info valueForKey:@"orderId"];
//
//        [DataStoreService putString:self.OrderNo withId:kDataStoreReceipOrderID intoTable:Device];
//
//        if (kIsEmpty(self.OrderNo)) {
//            [OCProgress_HUD showErrorWithStatus:@"订单号为空"];
//            return;
//        }
//        //苹果支付ID
//        if (kIsEmpty(storeKitModel.productionID)) {
//            [OCProgress_HUD showErrorWithStatus:@"苹果支付ID为空"];
//            return;
//        }
//
//        NSSet *set = [[NSSet alloc] initWithObjects:storeKitModel.productionID, nil];
//        self.request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
//        self.request.delegate = self;
//        [self.request start];
//
//    } failure:^(int code, NSString * _Nonnull msg) {
//        [OCProgress_HUD showErrorWithStatus:msg];
//    }];
}

#pragma mark ------- Private Methods -------

- (void)recordTransaction:(SKPaymentTransaction *)transaction {
    // Optional: Record the transaction on the server side...
    //记录当前购买成功的商品
    // NSLog(@"recordTransaction");
}

- (void)provideContent:(NSString *)productIdentifier {
     DEBUGLOG(@"provideContent %@", productIdentifier);
    //针对购买的商品，提供不同的服务。
    [_purchasedProducts addObject:productIdentifier];
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    //NSLog(@"completeTransaction...");
    [self recordTransaction:transaction];
    [self provideContent:transaction.payment.productIdentifier];
    [self verifyReceipt:transaction];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    [self recordTransaction:transaction];
    [self provideContent: transaction.originalTransaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    [OCProgress_HUD showErrorWithStatus:@"用户已恢复购买"];
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    [OCProgress_HUD dismiss];
    
    if (transaction.error.code != SKErrorPaymentCancelled) {
        [OCProgress_HUD showErrorWithStatus:transaction.error.localizedDescription];
        DEBUGLOG(@"Transaction error: %@", transaction.error.localizedDescription);
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [OCProgress_HUD showErrorWithStatus:@"支付取消"];
        });
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)panDuanJiaoYanWith:(BOOL)showTips {
//    if ([UserService isLoginUserAndPresent]) {
//        NSString *receiptStr = [DataStoreService getStringById:kDataStoreReceiptData fromTable:Device];
//        if (kIsEmpty(receiptStr)) {
//            if (showTips) {
//                [OCProgress_HUD showErrorWithStatus:@"无订单可同步"];
//            }
//
//        } else {
//            [self PayCallBack_iosPayCallBackApi];
//        }
//    } else {
//        [OCProgress_HUD showErrorWithStatus:@"无订单可同步"]
//    }
    
}

#pragma mark ------- SKProductsRequestDelegate -------

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    self.products = response.products;
    self.request = nil;
    for (SKProduct *product in response.products) {
        DEBUGLOG(@"已获取到产品信息 %@,%@,%@", product.localizedTitle, product.localizedDescription, product.price);
        self.product = product;
    }
    if (!self.product) {
        [OCProgress_HUD showErrorWithStatus:@"无法获取商品信息，请联系客服"];
        return;
    }
    //3.获取到产品信息，加入支付队列
    SKPayment *payment = [SKPayment paymentWithProduct:self.product];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

#pragma mark ------- SKPaymentTransactionObserver -------

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                DEBUGLOG(@"商品添加进列表");
                break;
            case SKPaymentTransactionStatePurchased:
                DEBUGLOG(@"交易完成");
                if (transaction.originalTransaction) {
                    // 自动续费
                    DEBUGLOG(@"自动续费 -- %@", transaction.originalTransaction);
                    NSString *orderId = [DataStoreService getStringById:kDataStoreReceipOrderID fromTable:Device];
                    if (!kIsEmpty(orderId)) {
                        // 有订单号，证明是第一次下单
                        [self completeTransaction:transaction];
                    } else {
                        [OCProgress_HUD dismiss];
                        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                    }
                    
                } else {
                    [self completeTransaction:transaction];
                }
                
                break;
            case SKPaymentTransactionStateFailed:
                DEBUGLOG(@"交易失败");
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                DEBUGLOG(@"已经购买过商品");
                [self restoreTransaction:transaction];
            case SKPaymentTransactionStateDeferred:
                DEBUGLOG(@"最终状态未确定");
            default:
                break;
        }
    }
}

#pragma mark ------- 服务器验证购买凭据 -------

- (void)verifyReceipt:(SKPaymentTransaction *)transaction {
    
    [DataStoreService putString:@"1" withId:kDataStoreBenDiVip intoTable:Device];

    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
    NSString *receiptStr = [receipt base64EncodedStringWithOptions:0];
    
    if (!receipt) {
        [OCProgress_HUD showErrorWithStatus:@"交易凭证为空验证失败"];
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        return;
    }
    
    if ([OCUserService share].isVisitorsLogin) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [OCProgress_HUD showSuccessWithStatus:@"开通成功"];
        });
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAppleApySuccess object:nil];
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        return;
    }
    
    NSString *orderID = [DataStoreService getStringById:kDataStoreReceipOrderID fromTable:Device];
    [DataStoreService putString:orderID withId:kDataStoreReceipNeed_OrderID intoTable:Device];
    
    [DataStoreService putString:receiptStr withId:kDataStoreReceiptData intoTable:Device];
//    transaction.originalTransaction.transactionIdentifier
    [DataStoreService putString:transaction.transactionIdentifier withId:kDataStoreReceipTransactionIdentifier intoTable:Device];
    [self PayCallBack_iosPayCallBackApi];

    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)PayCallBack_iosPayCallBackApi {
    // 有订单号
    NSDictionary *dict = @{@"receipt_data": [DataStoreService getStringById:kDataStoreReceiptData fromTable:Device] ?: @"",
                           @"orderId": [DataStoreService getStringById:kDataStoreReceipNeed_OrderID fromTable:Device] ?: @"",
                           @"ext": [DataStoreService getStringById:kDataStoreReceipTransactionIdentifier fromTable:Device] ?: @"",
                           @"automatic" : [DataStoreService getStringById:kDataStoreReceipAutomatic fromTable:Device] ?: @"",
    };
    dispatch_async(dispatch_get_main_queue(), ^{
        [OCProgress_HUD showWithStatus:@"正在校验，请稍后"];
    });
    
//    [NetworkService postWithUrlEnumName:PayCallBack_iosPayCallBack parameters:dict success:^(int code, id  _Nonnull info, NSString * _Nonnull msg) {
//
//        [DataStoreService deleteObjectById:kDataStoreReceiptData fromTable:Device];
//        [DataStoreService deleteObjectById:kDataStoreReceipNeed_OrderID fromTable:Device];
//        [DataStoreService deleteObjectById:kDataStoreReceipTransactionIdentifier fromTable:Device];
//        [DataStoreService deleteObjectById:kDataStoreReceipAutomatic fromTable:Device];
//        [OCProgress_HUD showSuccessWithStatus:@"开通成功"];
//        [[UserService share] userGetVipInfoApi];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAppleApySuccess object:nil];
//
//    } failure:^(int code, NSString * _Nonnull msg) {

//    }];
}

@end
